package com.hezhiqin.lock;

import java.util.concurrent.Semaphore;

/**
 * @program: homeWork
 * @description:
 * @author: hezhiqin
 * @create: 2019-12-29 15:08
 */
public class SemphoreDemo {

    //限流

    //permits 令牌

    //公平和非公平


    static class Car extends Thread{

        private int num;

        private Semaphore semaphore;


        public  Car (int num,Semaphore semaphore){
            this.num =num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();//获得令牌，拿不到就阻塞
                System.out.println("第"+num+"抢占一个车位");
                Thread.sleep(2000);
                System.out.println("第"+num+"开走");
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        Semaphore semaphore
                 = new Semaphore(5);

        for (int i = 0;i<10; i++){
            new Car(i,semaphore).start();
        }
    }

}
